const request = require("request")
const jsdom = require("jsdom")
let { JSDOM } = jsdom
let {songDetailTable} =require("./songDetailTable")
module.exports={
    getSongDetailData:function(req,res,err){
        let body=JSON.parse(Object.keys(req.body)[0]) //前端转为对象
        let mid=body.mid
        // console.log(mid)
        songDetailTable.find({
            songMid:mid
        }).then(data=>{
            if(Number(data)===0){  //判断数据库是否已经有数据 没有则创建
                request({
                    method:"GET",
                    url: "https://i.y.qq.com/v8/playsong.html",
                    qs: {
                        "songmid":mid
                    },
                    headers: {
                        "user-agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1"
                    }
                }, (err, response, body) => {
                    let dom = new JSDOM(body, { runScripts: "dangerously" })
                    console.log(dom.window.songlist)
                    let songData = dom.window.songlist[0]
                        let finalData = {
                            songMid: songData.songmid, 
                            m4aUrl: songData.m4aUrl, 
                            songName: songData.songname, 
                            playTime: songData.playTime, 
                            songPic: songData.pic
                        }
                        res.send(finalData)
                        songDetailTable.create(finalData)
                })
                
            }else{
                console.log("数据库已经有数据")
                res.send(data[0])
            }
        })
    }
}

